<?php
/*
* @version 0.3
* @package Joomla
* @subpackage FLEXIcontent
* @copyright (C) 2011 krapaic - and all the rest
* @license GNU/GPL v2
*/
defined('_JEXEC') or die('Restricted access');

jimport('joomla.event.plugin');

class plgFlexicontent_fieldsSfmp3Player extends JPlugin 
{
    function plgFlexicontent_fieldsSfmp3Player(&$subject, $params)
    {
        parent::__construct($subject, $params);
        JPlugin::loadLanguage('plg_flexicontent_fields_sfmp3player', JPATH_ADMINISTRATOR);
    }
    function onDisplayField(&$field, $item)
    {
        if ($field->field_type != 'sfmp3player') return;

        $document                     = &JFactory::getDocument();
        $flexiparams                 = &JComponentHelper::getParams('com_flexicontent');
        $mediapath                     = $flexiparams->get('media_path', 'components/com_flexicontent/medias');
        $app                         = &JFactory::getApplication();
        $client                     = $app->isAdmin() ? '../' : '';
        $clientpref                 = $app->isAdmin() ? '' : 'administrator/';
        $js                         = "
        function randomString() 
        {
            var chars                 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
            var string_length         = 6;
            var randomstring         = '';
            for (var i=0; i<string_length; i++) {
                var rnum             = Math.floor(Math.random() * chars.length);
                randomstring         += chars.substring(rnum,rnum+1);
            }
            return                     randomstring;
        }

        function qfSelectFile".$field->id."(id, file, remote) 
        {
            
            var name                 = 'a_name'+id;
            var ixid                 = randomString();
            
            // HTML ELEMENTS
            var filelist             = document.getElementById('sortables_".$field->id."');
            var li                     = document.createElement('li');
            // labels
            var mp3title_label         = document.createElement('label');
            var mp3link_label         = document.createElement('label');
            var mp3file_label         = document.createElement('label');
            // input and values
            var mp3file                = document.createElement('a');
            var mp3title             = document.createElement('input');
            var mp3link             = document.createElement('input');
            var button                 = document.createElement('input');
            var hid                    = document.createElement('input');
            // drag span and separator
            var span                = document.createElement('span');
            var img                    = document.createElement('img');    
            var brsep                = document.createElement('br');
                
            // TYPES
            button.type             = 'button';
            mp3title.type             = 'text';
            mp3link.type             = 'text';
            hid.type                 = 'hidden';
            
            // NAMES
            button.name             = 'removebutton_'+id;
            mp3title.name             = '".$field->name."['+ixid+'][title]';
            mp3link.name            = '".$field->name."['+ixid+'][link]';
            hid.name                 = '".$field->name."['+ixid+'][file]';
            
            // IDS
            button.id                 = 'removebutton_'+id;
            mp3title.id             = 'mp3title'+id;
            mp3link.id                 = 'mp3link'+id;
            hid.id                     = ixid;
            
            // VALUES
            if (typeof remote != 'undefined'){
            mp3link.value             = file;
            mp3title.value             = file;}
            hid.value                 = id;
            button.value             = '"     . JText::_('FLEXI_REMOVE_FILE') . "';
            mp3file.href             = '"     . $client . $mediapath . "'+file;
            mp3file.innerHTML        = file;
            
            // LABELS HTML
            mp3link_label.htmlFor     = 'mp3link'+id;
            mp3title_label.htmlFor     = 'mp3title'+id;
            mp3title_label.innerHTML= '"     . JText::_('SFMP3PLAYER_SOURCE_MP3_TITLE') . "';
            mp3file_label.innerHTML = '"     . JText::_('SFMP3PLAYER_SOURCE_MP3') . "';
            mp3link_label.innerHTML = '"     . JText::_('SFMP3PLAYER_SOURCE_MP3_LINK') . "';
            
            // other minor stuff
            mp3link.size             = '50';
            mp3file.alt             ='"     . JText::_('FLEXI_CLICK_TO_DRAG') . "';
            img.src                 = '"     . $clientpref . "components/com_flexicontent/assets/images/move3.png';
            img.alt                 ='"     . JText::_('FLEXI_CLICK_TO_DRAG') . "';
            
            // Css class
            $(li).addClass('minigallery');
            $(mp3file).addClass('mp3name');
            $(span).addClass('drag');
            $(button).addClass('fcbutton');
            $(button).addEvent('click', function() {deleteField" . $field->id . "(this)});
            
            // Attach li to document            
            filelist.appendChild(li);
            // mp3 filename
            li.appendChild(mp3file_label);
            li.appendChild(mp3file);
            // mp3 title
            li.appendChild(mp3title_label);
            li.appendChild(mp3title);
            // mp3 remote url
            li.appendChild(mp3link_label);
            li.appendChild(mp3link);
            // serparator
            li.appendChild(brsep);
            // remove button
            li.appendChild(button);
            // hidden id of file tables
            li.appendChild(hid);
            // drag element
            li.appendChild(span);
            span.appendChild(img);

            new Sortables($('sortables_" . $field->id . "'), {
                'handles': $('sortables_" . $field->id . "').getElements('span.drag'),
                'onDragStart': function(element, ghost){
                    ghost.setStyles({
                    'list-style-type': 'none',
                    'opacity': 1
                    });
                    element.setStyle('opacity', 0.3);
                },
                'onDragComplete': function(element, ghost){
                    element.setStyle('opacity', 1);
                    ghost.remove();
                    this.trash.remove();
                }
            });
        }

        function deleteField" . $field->id . "(el) 
        {
            var field                = $(el);
            var row                    = field.getParent();
            var fx                    = row.effects({duration: 300, transition: Fx.Transitions.linear});

            fx.start({
                'height': 0,
                'opacity': 0
            }).chain(function(){
                row.remove();
            });
        }
        function addRemoteMp3()
        {
            var regexpUrl             = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
            var remoteUrl            = document.getElementById('urlRemoteMp3').value;
            
            if (regexpUrl.test(remoteUrl)){
                document.getElementById('urlRemoteMp3').value=''; //clean input
                qfSelectFile" . $field->id . "(0, remoteUrl,true);
                
            } else    {
                alert('" . JText::_('SFMP3PLAYER_JSERRORMP3URL'). "');
            }
        }
        ";
        $document->addScriptDeclaration($js);
        // add the drag and drop sorting feature
        $js                         = "
            window.addEvent('domready', function(){
                new Sortables($('sortables_" . $field->id . "'), {
                    'handles': $('sortables_" . $field->id . "').getElements('span.drag'),
                    'onDragStart': function(element, ghost){
                        ghost.setStyles({
                           'list-style-type': 'none',
                           'opacity': 1
                        });
                        element.setStyle('opacity', 0.3);
                    },
                    'onDragComplete': function(element, ghost){
                        element.setStyle('opacity', 1);
                        ghost.remove();
                        this.trash.remove();
                    }
                    });
                });
            ";
        $document->addScriptDeclaration($js);

        $css                         = '
            #sortables_' . $field->id . ' {margin:0 0 10px 0;padding:0px;list-style:none; white-space: nowrap;}
            #sortables_' . $field->id . ' li {list-style: none;height: 130px;border-bottom:1px solid black}
            #sortables_' . $field->id . ' li a.mp3name {padding: 0;margin: 0 0 -5px 0;}
            #sortables_' . $field->id . ' li input { cursor: text;}
            #sortables_' . $field->id . ' li input[type=text] {width:500px;}
            #sortables_' . $field->id . ' li label { display:block;font-family:verdana;font-size:10px;font-weight:bold;}
            #sortables_' . $field->id . ' li input.fcbutton, .fcbutton {cursor:pointer;margin-left:3px;}
            span.drag img                 {margin:-4px 8px;cursor:move;}
            #sortables_' . $field->id . ' label,
            #sortables_' . $field->id . ' img, 
            #sortables_' . $field->id . ' input {vertical-align: middle;}';
               
        $document->addStyleDeclaration($css);

        $move                             = JHTML::image ('administrator/components/com_flexicontent/assets/images/move3.png', JText::_('FLEXI_CLICK_TO_DRAG'));

        JHTML::_('behavior.modal', 'a.modal_' . $field->id);

        $i = 0;
        $field->html     = '<ul id="sortables_' . $field->id . '">';

        if ($field->value) 
        {
            foreach($field->value as $value) 
            {
                $value                     = unserialize($value);
                $field->html             .= '<li>';
                $filename                 = $this->getFileName($value['file']);
                $src                     = (trim($value['link'])!=''? $value['link'] : $client . $mediapath . "/" . $filename->filename) ;
                $filelink                =  (trim($value['link'])!=''? $value['link'] : $client . $mediapath . "/" . $filename->filename) ; 
                $field->html             .= '<label>'. JText::_('SFMP3PLAYER_SOURCE_MP3') . '</label><a href="' . $src . '">'. $filelink . '</a>';
                $field->html             .= $this->plgFlexicontent_fieldsSfmp3player_renderPlayer($src,
                                                                                                 $value['title'],
                                                                                                $field, true);                
                $field->html             .= '<label for="mp3title' . $i . '">' . JText::_('SFMP3PLAYER_SOURCE_MP3_TITLE') . '</label>';
                $field->html             .= '<input type="text" size="80" id="mp3title' . $i . '" name="' . $field->name . '[' . $i . '][title]" value="' . $value['title'] . '" />';
                $field->html             .= '<label for="mp3link' . $i . '">' . JText::_('SFMP3PLAYER_SOURCE_MP3_LINK') . '</label>';
                $field->html             .= '<input type="text" size="80" id="mp3link' . $i . '" name="' . $field->name . '[' . $i . '][link]" value="' . $value['link'] . '" />';
                $field->html             .= '<br /><input type="hidden" id="a_id' . $i . '" name="' . $field->name . '[' . $i . '][file]" value="' . $value['file'] . '" />';
                $field->html             .= '<input class="inputbox fcbutton" type="button" onclick="deleteField' . $field->id . '(this);" value="' . JText::_('FLEXI_REMOVE_FILE') . '" />';
                $field->html             .= '<span class="drag">' . $move . '</span>';
                $field->html             .= '</li>';
                $i++;
            }
        }
        
        $linkfsel                         = JRoute::_('index.php?option=com_flexicontent&amp;view=fileselement&amp;tmpl=component&amp;filter_js=file&amp;filter_secure=M&amp;extallow=mp3&amp;index=' . $i . '&amp;field=' . $field->id.'&amp;'.JUtility::getToken().'=1');
        $field->html                     .= "
                        </ul>
                        <div class=\"button-add\">
                            <div class=\"blank\">
                                <label><strong>". JText::_('SFMP3PLAYER_LOCALEMP3') . "</strong></label> <a id=\"linkAttachMp3\" class=\"modal_" . $field->id . "\" title=\"" . JText::_('SFMP3PLAYER_ATTACHMP3') . "\" href=\"" . $linkfsel . "\" rel=\"{handler: 'iframe', size: {x:window.getSize().scrollSize.x-100, y: window.getSize().size.y-100}}\">" . JText::_('SFMP3PLAYER_ATTACHMP3') . "</a>
                                <br /><br />
                                <label><strong>". JText::_('SFMP3PLAYER_ADDREMOTEMP3INPUT') ."</strong></label>
                                <input id=\"urlRemoteMp3\" class=\"inputbox\" type=\"text\" size=\"50\" name=\"urlRemoteMp3\" />                                
                                <a id=\"addRemoteMp3\" href=\"javascript:void(0)\" onclick=\"addRemoteMp3();\">". JText::_('SFMP3PLAYER_ADDREMOTEMP3BUTTON') ." </a> 
                            </div>
                        </div>
                        ";
    }
    function onDisplayFieldValue(&$field, $item, $values = null, $prop = 'display')
    {
        $field->label                     = JText::_($field->label);
        $flexiparams                     = &JComponentHelper::getParams('com_flexicontent');
        $mediapath                         =  $flexiparams->get('media_path', 'components/com_flexicontent/media');
        // execute the code only if the field type match the plugin type
        if ($field->field_type != 'sfmp3player') return;
        $values                         = $values ? $values : $field->value ;
        if ($values) 
        {
            global                         $mainframe;
            $temp_path                    = "";
            $temp_title                    = "";
            foreach ($values as $value) 
            {
                $value                     = unserialize($value);
                $filename                 = $this->getFileName($value['file']);
                $temp_title             .= trim($value['title']) . "|" ;
                if (trim($value['link']) !='') {
                         $temp_path         .= trim($value['link']) ."|";}
                else {    $temp_path        .= trim($mediapath . '/' . $filename->filename) ."|";}
            }
            $temp_path                    = substr($temp_path, 0, -1); 
            $temp_title                    = substr($temp_title, 0, -1); 
            $field-> {$prop}             = $this->plgFlexicontent_fieldsSfmp3player_renderPlayer($temp_path,
                                                                                                 $temp_title,
                                                                                                $field);
        }
    }

    function onBeforeSaveField(&$field, &$post, $file)
    {
        if ($field->field_type != 'sfmp3player') return;

        global                             $mainframe;
        $newpost                         = array();
        $new                             = 0;
        foreach ($post as $n => $v) 
        {
            if ($post[$n]['file'] != '') 
            {
                $newpost[$new]['file']     = $post[$n]['file'];
                $newpost[$new]['title'] = ($post[$n]['title']==''?'Track ' . $n: $post[$n]['title']);
                
                if (!preg_match("#^http|^https|^ftp#i", $post[$n]['link']) && $post[$n]['link']) 
                {
                    $newpost[$new]['link'] = 'http://' . $post[$n]['link'];
                } 
                else 
                {
                    $newpost[$new]['link'] = $post[$n]['link'];
                }
                $new++;
            }
        }
        $post = $newpost;
        $searchindex = '';
        foreach ($post as $v) 
        {
            $searchindex                 .= $v['title'];
            $searchindex                 .= ' ';
            $searchindex                 .= $v['link'];
        }
        $searchindex                     .= ' | ';
        $field->search                     = $searchindex;
    }

    function getFileName($value)
    {
        $db                             = &JFactory::getDBO();
        $query                             = 'SELECT filename, altname, ext FROM #__flexicontent_files'
                                        . ' WHERE id = ' . (int) $value ;
        $db->setQuery($query);
        $filename                         = $db->loadObject();
        return                             $filename;
    }
    
    function plgFlexicontent_fieldsSfmp3player_renderPlayer($mp3_list, $mp3_titles, &$fieldelement, $usesingle=false)
    {
        
        $ListMp3                        = $mp3_list;
        $ListTitle                        = $mp3_titles;
        $ListTitleUrl                     = urlencode($ListTitle);
        $plugin                         = & JPluginHelper::getPlugin('flexicontent_fields','sfmp3player');
        $params                         = new JParameter($plugin->params);    
        $display_label                    = $fieldelement->parameters->get('display_label');
        $pluginclass_sfx                = $fieldelement->parameters->get('pluginclass_sfx');
        $player_width                     = $fieldelement->parameters->get('player_width');
        
        $app                             = &JFactory::getApplication();
        $usesingle                         = $app->isAdmin()? true: $fieldelement->parameters->get('player_showlist');
                
        $player_height                     = ($usesingle==true? 21: $fieldelement->parameters->get('player_height'));
        $player_showinfo                 = $fieldelement->parameters->get('player_showinfo');
        $player_showvolume                 = $fieldelement->parameters->get('player_showvolume');
        $player_volume                     = $fieldelement->parameters->get('player_volume');
        $player_volumewidth             = $fieldelement->parameters->get('player_volumewidth');
        $player_volumeheight             = $fieldelement->parameters->get('player_volumeheight');
        $player_autoplay                 = $fieldelement->parameters->get('player_autoplay');
        $player_loop                     = $fieldelement->parameters->get('player_loop');
        $player_shuffle                 = $fieldelement->parameters->get('player_shuffle');
        $player_showloading             = $fieldelement->parameters->get('player_showloading');
        $player_loadingbarcolor         = $fieldelement->parameters->get('player_loadingbarcolor');
        $player_showplaylistnumbers     = $fieldelement->parameters->get('player_showplaylistnumbers');
        $player_playlistcolor             = $fieldelement->parameters->get('player_playlistcolor');
        $player_playlistalphacolor         = $fieldelement->parameters->get('player_playlistalphacolor');
        $player_showslider                 = $fieldelement->parameters->get('player_showslider');
        $player_sliderwidth             = $fieldelement->parameters->get('player_sliderwidth');
        $player_sliderheight             = $fieldelement->parameters->get('player_sliderheight');
        $player_slidercolor1             = $fieldelement->parameters->get('player_slidercolor1');
        $player_sliderovercolor         = $fieldelement->parameters->get('player_sliderovercolor');
        $player_bgimage                 = $fieldelement->parameters->get('player_bgimage');
        $player_bgcolor                 = $fieldelement->parameters->get('player_bgcolor');
        $player_bgcolor1                 = $fieldelement->parameters->get('player_bgcolor1');
        $player_bgcolor2                 = $fieldelement->parameters->get('player_bgcolor2');
        $player_textcolor                 = $fieldelement->parameters->get('player_textcolor');
        $player_currentmp3color         = $fieldelement->parameters->get('player_currentmp3color');
        $player_buttonwidth             = $fieldelement->parameters->get('player_buttonwidth');
        $player_buttoncolor             = $fieldelement->parameters->get('player_buttoncolor');
        $player_buttonovercolor         = $fieldelement->parameters->get('player_buttonovercolor');
        $player_scrollbarcolor             = $fieldelement->parameters->get('player_scrollbarcolor');
        $player_scrollbarovercolor         = $fieldelement->parameters->get('player_scrollbarovercolor');
        $player_slidercolor2             = $fieldelement->parameters->get('player_slidercolor2');
        $player_flashmode                 = $fieldelement->parameters->get('player_flashmode');
        $player_copyright                 = $fieldelement->parameters->get('player_copyright');
        $player_bgimage                    = $fieldelement->parameters->get('player_bgimage');
        $swf                            = JURI::root() . 'plugins/flexicontent_fields/sfmp3player/swf/sfmp3player.swf';
        $swfExpressInstall                = JURI::root() . 'plugins/flexicontent_fields/sfmp3player/swf/expressInstall.swf';
        $js_sfmp3player                    = '' .
        
        // add random for backend display
        $length                         = 5;
        $characters                     = '0123456789abcdefghijklmnopqrstuvwxyz';
        $tstring                         = '';    
        for ($p = 0; $p < $length; $p++) {$tstring .= $characters[mt_rand(0, strlen($characters))];}
        $idRandomPlayer                    = "sfmp3Player_" . $fieldelement->id .  "_" . $tstring;
    
        $js_sfmp3player                    = '
         var flashvars= {}; 
         var attr= {}; 
         var params= {};
         params.menu= "false"; 
         params.wmode= "opaque";
         flashvars.showlist= "1";
         attr.id="'                     . $idRandomPlayer . '";
         attr.name="'                     . $idRandomPlayer . '";
         params.bgcolor= "'                . $player_bgcolor.'"; 
         flashvars.mp3= "'                . $ListMp3.'";
         flashvars.title= "'            . $ListTitleUrl.'";
         flashvars.showinfo= "'            . $player_showinfo.'";
         flashvars.showvolume= "'        . $player_showvolume.'";
         flashvars.volume= "'            . $player_volume.'";
         flashvars.volumewidth= "'        . $player_volumewidth.'";
         flashvars.volumeheight= "'        . $player_volumeheight.'";
         flashvars.autoplay= "'            . $player_autoplay.'";
         flashvars.loop= "'                . $player_loop.'";
         flashvars.shuffle= "'            . $player_shuffle.'";
         flashvars.showloading= "'        . $player_showloading.'";
         flashvars.loadingcolor= "'        . $player_loadingbarcolor.'";
         flashvars.showplaylistnumbers="'. $player_showplaylistnumbers.'";
         flashvars.playlistcolor= "'    . $player_playlistcolor.'";
         flashvars.playlistalpha= "'    . $player_playlistalphacolor.'";
         flashvars.showslider= "'        . $player_showslider.'";
         flashvars.sliderwidth= "'        . $player_sliderwidth.'";
         flashvars.sliderheight= "'        . $player_sliderheight.'";
         flashvars.slidercolor1= "'        . $player_slidercolor1.'";
         flashvars.slidercolor2= "'        . $player_slidercolor2.'";
         flashvars.sliderovercolor= "'    . $player_sliderovercolor.'";
         flashvars.bgcolor= "'            . $player_bgcolor.'";
         flashvars.bgcolor1= "'            . $player_bgcolor1.'";
         flashvars.bgcolor2= "'            . $player_bgcolor2.'";
         flashvars.textcolor= "'        . $player_textcolor.'";
         flashvars.currentmp3color= "'    . $player_currentmp3color.'"
         flashvars.buttonwidth= "'        . $player_buttonwidth.'";
         flashvars.buttoncolor= "'        . $player_buttoncolor.'";
         flashvars.buttonovercolor= "'    . $player_buttonovercolor.'";
         flashvars.scrollbarcolor= "'    . $player_scrollbarcolor.'";
         var stageW= "'                    . $player_width .'"; 
         var stageH= "'                    . $player_height.'";'.
        ($player_bgimage == -1 ? "" : 'flashvars.skin="plugins/flexicontent_fields/sfmp3player/images/' . $player_bgimage . '";') .
        'swfobject.embedSWF("'.$swf.'", attr.id, stageW, stageH, "9.0.124","'. $swfExpressInstall . '" , flashvars, params, attr);';
        
        // check if SWFObject is alreay include in header (for example by Gallery_Flashmatic)
        $document                         = &JFactory::getDocument();
        $headerstuff                     = $document->getHeadData();
        $scripts                         = $headerstuff['scripts'];
        $jsForRemove                     = array('swfobject.js');
        $swfFound                        = 0;
        foreach ($scripts as $key => $value)
        {
                foreach ($jsForRemove as $js)
                {
                    if (strpos($key, $js) !== false) $swfFound++;
                }
        }
        if ($swfFound == 0)     
        {
            $document->addScript(JURI::root().'plugins/flexicontent_fields/sfmp3player/js/swfobject.js');
        }
        $document->addStyleSheet(JURI::root().'plugins/flexicontent_fields/sfmp3player/css/sfmp3player.css' );
        $document->addScriptDeclaration($js_sfmp3player);
        
        $code                            = '<div class="smp3player_container'.$pluginclass_sfx.'">'
                                            . '<div id="' . $idRandomPlayer . '">'.
                                                JText::_('SFMP3PLAYER_SOURCE_ERRORE_PLAYER_ADOBE_LINK'). 
                                              '</div>' .
                                          '</div>' .
                                          '<div class="smp3player_clear"></div>';
        
        return $code;    
    }
}